<template>
  <div class="app-container calendar-list-container">
    <el-button class="filter-item" type="primary" @click="cancel">返回</el-button>
    <el-button class="filter-item" type="success" @click="addGoods">添加验布</el-button>
    <!-- <el-button class="filter-item" type="danger" @click="addStockGoods">添加商品</el-button>-->
    <el-button class="filter-item" type="primary" @click="save">保存</el-button>
    <div class="w-body">
      <el-form :model="entity" :rules="dataRule" ref="entity" label-width="80px" size="small">
        <el-row>
          <el-col :span="6">
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="entity.customerName" :readonly="true">
                <el-button slot="append" icon="el-icon-search" @click="addCustomer"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="仓库列表" prop="warehouseCode">
              <el-select v-model="entity.warehouseCode" placeholder="请选仓库">
                <el-option v-for="(type, index) in warehouseList" :label="type.warehouseName" :value="type.warehouseCode" :key="index"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="外部单号" prop="outBusinessCode">
              <el-input v-model="entity.outBusinessCode">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="总数量">
              {{totalAmount}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="雇员" prop="employeeName">
              <el-input v-model="entity.employeeName" :readonly="true">
                <el-button slot="append" icon="el-icon-search" @click="addOwner"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="加工单价" prop="price">
              <el-input v-model="entity.price" type="number"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="卷数" prop="total">
              <el-input v-model="entity.total" type="number" :readonly="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div class="w-table">
              <grid gridTitle="物品信息" :columns="columns" :enableEdit="true" :loading="false" ref="mainGrid" height="auto" diffHeight="270" :pagination="false" @delete="doDelete"
                @copy="doCopy" :permissions="permissions" :multi="false" :keyEditStep="5" @editDataChange="editDataChange" @rowDataChange="rowDataChange"></grid>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <GridDialog ref="ownerGridDialog" :url="ownerUrl" :columns="userColunms" @select="selectOwnerData" :permissions="permissions" :queryEntity="{key: 'CUSTOMER'}" :multi="true"
      :selectSize="2">
    </GridDialog>
    <GridDialog ref="customerGridDialog" :url="customerUrl" :columns="customerColumns" @select="selectCustomerData" :permissions="permissions" :queryEntity="customerQueryEntity"
      :pagination="false" :queryList="customerQueryList"></GridDialog>
    <GridDialog ref="goodsGridDialog" :multi="true" :url="goodsUrl" :columns="goodsColumns" @select="selectGoodsData" :permissions="permissions" :queryEntity="goodsQueryEntity"
      :pagination="false"></GridDialog>
    <GridDialog ref="stockGridDialog" :multi="true" :url="stockGoodsUrl" :columns="goodsColumns" @select="selectGoodsData" :permissions="permissions"
      :queryEntity="goodsQueryEntity" :pagination="false" :queryList="modelQueryList"></GridDialog>
  </div>
</template>

<script>
import request from '@/router/axios'
import { Message, MessageBox } from 'element-ui'
import url from '@/const/apiURL'
import GridDialog from '@/components/GridDialog'
import grid from '@/components/Grid'
import { mapGetters } from 'vuex'
import { queryField } from '@/const/query'
import { colunms } from '@/const/colunms'
import { dict } from '@/const/dict'

export default {
  components: { GridDialog, grid },
  data () {
    return {
      totalAmount: 0,
      customerQueryEntity: { customerType: 'HANDLE' },
      customerQueryList: queryField().customer,
      warehouseList: [],
      ownerUrl: url.USER_LIST_URL,
      stockGoodsUrl: url.BUSINESS_GOODS_LIST_URL,
      customerUrl: url.BUSINESS_CUSTOMER_URL,
      goodsUrl: url.BUSINESS_IN_GOODS_LIST_URL,
      modelQueryList: queryField().modelName,
      userColunms: colunms().userColumns,
      goodsCode: '',
      entity: {
        customerCode: '',
        customerName: '',
        warehouseCode: '',
        employeeName: '',
        price: 0,
        goods: []
      },
      goodsQueryEntity: {},
      columns: [
        { label: this.global.modelName, width: 80, prop: 'goodsName', align: 'left' },
        { label: this.global.modelProp, width: 80, prop: 'modelProp', align: 'left' },
        { label: '物料名称', width: 360, prop: 'materialName', align: 'left' },
        // { label: '物料类型', width: 100, prop: 'materialTypeName', align: 'center' },
        { label: '单位', width: 100, prop: 'unit', align: 'center', template: 'select', selectDatas: dict().Unit },
        { label: '序列号', width: 160, prop: 'serialNumber', align: 'center' },
        { label: '毛重', width: 100, prop: 'goodsWeight', align: 'center', template: 'edit', type: 'number', rowChange: true },
        { label: '净重', width: 100, prop: 'goodsNetWeight', align: 'center' },
        { label: '缸号', width: 160, prop: 'gangNo', align: 'center', template: 'edit', type: 'text' },
        { label: '卷数', width: 100, prop: 'total', align: 'center', template: 'edit', type: 'number' },
        { label: '数量', width: 120, prop: 'quantity', align: 'center', template: 'edit', type: 'number' },
        { label: '扣减', width: 80, prop: 'deleteQuantity', align: 'center' },
        { label: '顺序', width: 60, prop: 'indexSort', align: 'center' },
        { label: '备注', width: 200, prop: 'remark', align: 'center', template: 'edit', type: 'text' },
        { label: '操作', width: 100, prop: 'op', align: 'center', template: 'op', opList: [{ name: '删除', clickName: 'delete', auth: 'yes' }, { name: '复制', clickName: 'copy', auth: 'yes' }] }
      ],
      goodsColumns: colunms().goodsColumns,
      customerColumns: colunms().customerColumns,
      dataRule: {
        customerName: [{ required: true, message: '客户不能为空', trigger: 'blur' }],
        warehouseCode: [{ required: true, message: '仓库不能为空', trigger: 'blur' }],
        //    employeeName: [{ required: true, message: '雇员不能为空', trigger: 'blur' }],
        price: [{ required: true, message: '单价不能为空', trigger: 'blur' }],
        total: [{ required: true, message: '卷数不能为空', trigger: 'blur' }]
      }
    }
  },
  created () {
    this.businessCode = this.$route.query.businessCode
    this.code = this.$route.query.code
    this.index = this.$route.query.index
    this.goodsCode = this.$route.query.goodsCode,
      this.init()
  },
  computed: {
    ...mapGetters(['permissions'])
  },
  methods: {
    init () {
      this.initWarehouse()
      this.initData()
    },
    rowDataChange (row) {
      if (row) {
        this.$nextTick(() => {
          row.goodsNetWeight = (Number(row.goodsWeight) - Number(row.weightDiff || 0)).toFixed(1)
        })
        this.$forceUpdate();
      }
    },
    editDataChange () {
      let gridData = this.$refs['mainGrid'].getData()
      this.totalAmount = 0
      this.entity.total = 0
      if (gridData) {
        gridData.forEach(row => {
          this.totalAmount = (Number(this.totalAmount) + Number(row.quantity)).toFixed(2)
          this.entity.total = Number(this.entity.total) + Number(row.total || 0)
        })
      }
    },
    cancel () {
      if (this.index) {
        this.$router.push({ path: '/prod/business/hand', query: {} })
      } else {
        this.$router.push({ path: '/prod/business', query: { code: this.code, goodsCode: this.goodsCode, orderNo: this.entity.orderNo } })
      }
    },
    addOwner () {
      this.$refs['ownerGridDialog'].show()
    },
    selectOwnerData (rows) {
      this.entity.employee = rows[0].userCode
      this.entity.employeea = rows[1].userCode
      this.entity.employeeName = rows[0].userName + ',' + rows[1].userName
    },
    addCustomer () {
      this.$refs['customerGridDialog'].show()
    },
    selectCustomerData (row) {
      this.entity.customerName = row.customerName
      this.entity.customerCode = row.customerCode
      this.goodsQueryEntity.customerCode = row.customerCode
      this.$refs['mainGrid'].deleteAll()
    },
    addGoods () {
      if (this.entity.customerCode) {
        this.$refs['goodsGridDialog'].show()
      } else {
        MessageBox.alert("请选择客户")
      }
    },
    addStockGoods () {
      this.$nextTick(() => {
        this.$refs['stockGridDialog'].show()
      })
    },
    selectGoodsData (rows) {
      rows.forEach(row => {
        const rowData = {
          code: row.code,
          goodsCode: row.goodsCode || row.modelCode,
          goodsName: row.goodsName || row.modelName,
          modelName: row.goodsName,
          materialName: row.materialName,
          materialTypeName: row.materialTypeName,
          modelProp: row.modelProp,
          unit: row.unit,
          weightDiff: row.weightDiff,
          price: 0,
          outQuantity: row.quantity,
          total: row.total,
          batchNo: row.batchNo,
          serialNumber: row.serialNumber
        }
        this.$refs['mainGrid'].addRow(rowData)
        this.entity.total += row.total || 0
      })
    },
    save () {
      this.$refs['entity'].validate((valid) => {
        if (valid) {
          let purchase = this.entity
          purchase.goods = this.$refs['mainGrid'].getData()
          this.saveUrl(purchase).then(data => {
            if (data) {
              if (this.index) {
                this.$router.push({ path: '/prod/business/hand', query: {} })
              } else {
                this.$router.push({ path: '/prod/business', query: { code: this.code, goodsCode: this.goodsCode, orderNo: this.entity.orderNo } })
              }
            }
          })
        }
      })
    },
    doCopy (row) {
      const newRow = {
        goodsCode: row.goodsCode || row.modelCode,
        goodsName: row.goodsName || row.modelName,
        modelName: row.goodsName,
        materialName: row.materialName,
        materialTypeName: row.materialTypeName,
        modelProp: row.modelProp,
        unit: row.unit,
        weightDiff: row.weightDiff,
        price: 0,
        gangNo: row.gangNo,
        quantity: null,
        batchNo: row.batchNo,
        serialNumber: null
      }
      this.$refs['mainGrid'].addRow(newRow)
    },
    doDelete (row) {
      this.$refs['mainGrid'].deleteRow(row)
    },
    initWarehouse () {
      this.warehouseUrl().then(data => {
        if (data) {
          this.warehouseList = data
        }
      })
    },
    initData () {
      this.viewUrl(this.businessCode, 'IN').then(data => {
        if (data) {
          this.entity = data
          data.goods.forEach(row => {
            row.code = row.linkCode
            this.$refs['mainGrid'].addRow(row)
          })
          this.goodsQueryEntity.orderNo = data.orderNo
          this.goodsQueryEntity.stepCode = data.stepCode
          this.goodsQueryEntity.goodsCode = data.goodsCode
          this.entity.customerCode = data.customerCode
          this.goodsQueryEntity.customerCode = data.customerCode
          this.customerQueryEntity.orderNo = data.orderNo
          this.customerQueryEntity.stepCode = data.stepCode
          this.totalAmount += Number(data.quantity || 0)
          this.totalAmount = this.totalAmount.toFixed(2)

        }
      })
    },
    viewUrl (businessCode, businessType) {
      return request({
        url: url.BUSINESS_VIEW_URL,
        method: 'post',
        data: { key: 'key' },
        params: { businessCode, businessType }
      })
    },
    saveUrl (data) {
      return request({
        url: url.BUSINESS_EDIT_URL,
        method: 'post',
        data: data
      })
    },
    warehouseUrl () {
      return request({
        url: url.WAREHOUSE_USABLE_URL,
        method: 'post',
        data: { key: 'key' }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.w-body {
  padding-top: 8px;
}
.w-table {
  border: 1px solid #ebeef5;
}
.w-table-title {
  border: 1px solid #ebeef5;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
  word-break: break-all;
  line-height: 23px;
  display: inline-block;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  position: relative;
  vertical-align: middle;
  width: 100%;
  font-size: 14px;
  color: gray;
}
</style>
